﻿
using LuxsanCommunicationTool.Communication;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LuxsanTool.Tool
{
    public partial class UserControl_Other1Tool : UserControl
    {
        public UserControl_Other1Tool(Other1BaseTool _atlasTool)
        {
            InitializeComponent();
            m_Other1Tool = _atlasTool;

            InitialInPutValue();
            InitialOutputValue();
        }

        Other1BaseTool m_Other1Tool;


        DataTable dataTableInPutValue = new DataTable("InPutValue");
        DataTable dataTableOutputValue = new DataTable("OutputValue");


        #region  DataGriview 显示
        private void InitialInPutValue()
        {
            DataColumn taxColumn1 = new DataColumn("名称", typeof(string));
            DataColumn taxColumn2 = new DataColumn("类型");
            DataColumn taxColumn3 = new DataColumn("来源工站名", typeof(string));
            DataColumn taxColumn4 = new DataColumn("来源工具名", typeof(string));
            DataColumn taxColumn5 = new DataColumn("来源变量名", typeof(string));
            DataColumn taxColumn6 = new DataColumn("值");

            dataTableInPutValue.PrimaryKey = new DataColumn[] { dataTableInPutValue.Columns["名称"] };

            dataTableInPutValue.Columns.Add(taxColumn1);
            dataTableInPutValue.Columns.Add(taxColumn2);
            dataTableInPutValue.Columns.Add(taxColumn3);
            dataTableInPutValue.Columns.Add(taxColumn4);
            dataTableInPutValue.Columns.Add(taxColumn5);
            dataTableInPutValue.Columns.Add(taxColumn6);
        }

        private void InitialOutputValue()
        {
            DataColumn taxColumn1 = new DataColumn("名称", typeof(string));
            DataColumn taxColumn2 = new DataColumn("类型");
            DataColumn taxColumn3 = new DataColumn("值");

            dataTableOutputValue.PrimaryKey = new DataColumn[] { dataTableOutputValue.Columns["名称"] };

            dataTableOutputValue.Columns.Add(taxColumn1);
            dataTableOutputValue.Columns.Add(taxColumn2);
            dataTableOutputValue.Columns.Add(taxColumn3);
        }

        private void DeleteDataTable(DataTable _DataTable, string strDeleteName)
        {
            DataRow[] dataRows = _DataTable.Select("名称='" + strDeleteName + "'");
            foreach (DataRow dataRow in dataRows)
            {
                dataRow.Delete();
            }
        }

        private void ModifyDataTable(DataTable _DataTable, string _strNewValueName, string _strOldValueName)
        {

            DataRow[] dataRows = _DataTable.Select("名称='" + _strOldValueName + "'");
            foreach (DataRow dataRow in dataRows)
            {
                dataRow[0] = _strNewValueName;
            }
        }
        #endregion


        #region  SetSize 设定控件尺寸大小
        public void SetSize(int Width, int Height)
        {
            this.Size = new System.Drawing.Size(Width, Height);

        }
        #endregion

    

        #region  InPutValueParaToForm 参数到界面
        /// <summary>
        /// 参数到界面
        /// </summary>
        public void InPutValueParaToForm()
        {
            List<string> listKey = m_Other1Tool.m_ToolInputValue.Keys.ToList();
            List<ToolInputValue> listValue = m_Other1Tool.m_ToolInputValue.Values.ToList();

            if ( LuxsanProjectManage.Global.GetMainForm().InvokeRequired)
            {
                Tool.ToolDisDelegate displayDelegate = new Tool.ToolDisDelegate(InPutValueParaToForm);
                 LuxsanProjectManage.Global.GetMainForm().Invoke(displayDelegate);
            }
            else
            {
                for (int i = 0; i < listValue.Count; i++)
                {
                    DataRow[] dataRows = dataTableInPutValue.Select("名称='" + listKey[i] + "'");

                    if (dataRows.Count() == 0)
                        dataTableInPutValue.Rows.Add(listKey[i], listValue[i].strType, listValue[i].InPutResources.GetWorkName,
                             listValue[i].InPutResources.GetToolName, listValue[i].InPutResources.GetValueName, listValue[i].objValue);
                    else
                    {
                        foreach (DataRow dataRow in dataRows)
                        {
                            dataRow[0] = listKey[i];
                            dataRow[1] = listValue[i].strType;
                            dataRow[2] = listValue[i].InPutResources.GetWorkName;
                            dataRow[3] = listValue[i].InPutResources.GetToolName;
                            dataRow[4] = listValue[i].InPutResources.GetValueName;
                            dataRow[5] = listValue[i].objValue;
                        }
                    }
                }
                dtInPutValue.DataSource = dataTableInPutValue;
            };
        }

        #endregion

        #region  OutPutValueParaToForm 输出值到界面
        /// <summary>
        /// 输出参数到界面
        /// </summary>
        public void OutPutValueParaToForm()
        {
   
            List<string> listKey = m_Other1Tool.m_ToolOutPutValue.Keys.ToList();
            List<ToolOutPutValue> listValue = m_Other1Tool.m_ToolOutPutValue.Values.ToList();
            if ( LuxsanProjectManage.Global.GetMainForm().InvokeRequired)
            {
                Tool.ToolDisDelegate displayDelegate = new Tool.ToolDisDelegate(OutPutValueParaToForm);
                 LuxsanProjectManage.Global.GetMainForm().Invoke(displayDelegate);
            }
            else
            {
                // LuxsanProjectManage.Global.GetMainForm().Invoke(new MethodInvoker(delegate
                //{
                            for (int i = 0; i < listValue.Count; i++)
                            {
                                DataRow[] dataRows = dataTableOutputValue.Select("名称='" + listKey[i] + "'");


                                if (dataRows.Count() == 0)
                                    dataTableOutputValue.Rows.Add(listKey[i], listValue[i].strType, listValue[i].objValue);
                                else
                                {
                                    foreach (DataRow dataRow in dataRows)
                                    {
                                        dataRow[0] = listKey[i];
                                        dataRow[1] = listValue[i].strType;
                                        string strType = listValue[i].strType;

                                if (strType == LuxsanType.ArrayVarType.LuxsanVarTypeInt16Array)
                                {
                                    dataRow[2] = string.Join(",", listValue[i].objValue as Int16[]);
                                }
                                else if (strType == LuxsanType.ArrayVarType.LuxsanVarTypeDoubleArray)
                                {
                                    dataRow[2] = string.Join("", listValue[i].objValue as Double[]);
                                }
                                else
                                    dataRow[2] = listValue[i].objValue;

                                 }
                               }
                            }
                            dtOutPutValue.DataSource = dataTableOutputValue;
                  
                //}));
            }
        }
        #endregion

        #region AddScriptControl 添加脚本控件
        /// <summary>
        /// 添加脚本控件
        /// </summary>
        public void AddScriptControl(Control control,int _pageIndex=0)
        {
            Form ScriptForm = control as Form;
            ScriptForm.TopLevel = false;
            ScriptForm.FormBorderStyle = FormBorderStyle.None;
            tabPage1_2.Controls.Clear();
            tabPage1_2.Controls.Add(ScriptForm);
            //tabControl1.SelectedIndex = 1;
            ScriptForm.Show();
            ScriptForm.Dock = DockStyle.Fill;
        }
        #endregion

        #region  SetParaToForm 通讯参数到界面
        /// <summary>
        /// 通讯参数到界面
        /// </summary>
        public void SetParaToForm()
        {
            if ( LuxsanProjectManage.Global.GetMainForm().InvokeRequired)
            {
                Tool.ToolDisDelegate displayDelegate = new Tool.ToolDisDelegate(SetParaToForm);
                 LuxsanProjectManage.Global.GetMainForm().Invoke(displayDelegate);
            }
            else
            {
               
                swLog.Active = m_Other1Tool.m_bLogEnable;
                cbEnable.Checked = m_Other1Tool.m_bEnable;
                numDelayedTimeFront.Value = m_Other1Tool.m_iToolDelayTimeFront;
                numDelayedTimeBack.Value = m_Other1Tool.m_iToolDelayTimeBack;
            };
        }

        #endregion

        #region FormToSetPara  界面到运行状态命令
        /// <summary>
        /// 界面到运行状态命令
        /// </summary>
        public void FormToSetPara()
        {
            if ( LuxsanProjectManage.Global.GetMainForm().InvokeRequired)
            {
                Tool.ToolDisDelegate displayDelegate = new Tool.ToolDisDelegate(FormToSetPara);
                 LuxsanProjectManage.Global.GetMainForm().Invoke(displayDelegate);
            }
            else
            {
                m_Other1Tool.m_bLogEnable = swLog.Active;
                m_Other1Tool.m_bEnable = cbEnable.Checked;


                m_Other1Tool.m_iToolDelayTimeFront = (int)numDelayedTimeFront.Value;
                m_Other1Tool.m_iToolDelayTimeBack = (int)numDelayedTimeBack.Value;
            };
        }
        #endregion


        #region GetSelectedRowIndex 选择行
        /// <summary>
        /// 选择行
        /// </summary>
        /// <param name="dgv"></param>
        /// <returns></returns>
        private int GetSelectedRowIndex(DataGridView dgv)
        {
            if (dgv.Rows.Count == 0)
            {
                return 0;
            }

            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (row.Selected)
                {
                    return row.Index;
                }
            }
            return 0;
        }
        #endregion

        #region DisRunResult  显示运行结果
        /// <summary>
        /// 显示运行结果
        /// </summary>
        public void DisRunResult()
        {

            if ( LuxsanProjectManage.Global.GetMainForm().InvokeRequired)
            {
                Tool.ToolDisDelegate displayDelegate = new Tool.ToolDisDelegate(DisRunResult);
                 LuxsanProjectManage.Global.GetMainForm().Invoke(displayDelegate);
            }
            else
            {
               
                labTimeOut.Text = "耗时:" + m_Other1Tool.m_stopwatchStart.ElapsedMilliseconds.ToString() + "ms";
                if (m_Other1Tool.m_executeStatus.bStatus)
                    labMsg.ForeColor = Color.Black;
                else
                    labMsg.ForeColor = Color.Red;
                labMsg.Text = "信息:" + m_Other1Tool.m_executeStatus.bStatus + "->" + m_Other1Tool.m_executeStatus.strErrorMsg;
            };
        }
        #endregion

        #region  btnSetCommunication_Click 设定通讯
        private void btnSetCommunication_Click(object sender, EventArgs e)
        {
            if (LuxsanTool.MachineWorkManage.m_bStart)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("系统正在运行", "提示");
                return;
            }
            LuxsanBaseHelpLib.LogIn.User user = LuxsanBaseHelpLib.LogIn.LogIn.m_actCuurentUser;
            if (user.iAuthorityLevel < (int)LuxsanBaseHelpLib.LogIn.AuthorityLevel.Engineer)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("权限不足", "提示");
                return;
            }

            //int iWith = LuxsanTool.HelpForm.frmSetCommunication.m_Instance.Width;
            //int iHeight = LuxsanTool.HelpForm.frmSetCommunication.m_Instance.Height;

            //Point pitMousePosition = Control.MousePosition;
            //LuxsanTool.HelpForm.frmSetCommunication.m_Instance.SetDesktopLocation(pitMousePosition.X, pitMousePosition.Y - iHeight);
            LuxsanCommunicationTool.HelpForm.frmSetCommunication.m_Instance.Initial(m_Other1Tool.m_strCommunicationName);
            LuxsanCommunicationTool.HelpForm.frmSetCommunication.m_Instance.ShowDialog();
            if (!LuxsanCommunicationTool.HelpForm.frmSetCommunication.m_Instance.m_bOkCannel)
                return;

            string strComName = LuxsanCommunicationTool.HelpForm.frmSetCommunication.m_Instance.m_strComName;
            int iComType = LuxsanCommunicationTool.HelpForm.frmSetCommunication.m_Instance.m_iComType;

            LuxsanCommunicationTool.HelpForm.frmSetCommunication.m_Instance.Release();

            m_Other1Tool.m_strCommunicationName = strComName;
            m_Other1Tool.m_iCommunicationType = iComType;
            //显示输入值
            SetParaToForm();

        }


        #endregion

        #region BtnSave2_Click 保存
        private void BtnSave2_Click(object sender, EventArgs e)
        {
            if (LuxsanTool.MachineWorkManage.m_bStart)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("系统正在运行", "提示");
                return;
            }
            //LuxsanBaseHelpLib.LogIn.User user = LuxsanBaseHelpLib.LogIn.LogIn.m_actCuurentUser;
            //if (user.iAuthorityLevel < (int)LuxsanBaseHelpLib.LogIn.AuthorityLevel.Engineer)
            //{
            //    LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("权限不足", "提示");
            //    return;
            //}

            LuxsanBaseHelpLib.LogIn.LogIn.LogOut();
            LuxsanTool.frmLogIn _frmLogIn = new LuxsanTool.frmLogIn();
            _frmLogIn.ShowDialog();

            if (LuxsanBaseHelpLib.LogIn.LogIn.m_actCuurentUser.iAuthorityLevel < (int)LuxsanBaseHelpLib.LogIn.AuthorityLevel.Engineer)
            {
                //LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("权限不足", "提示");
                return;
            }

            if (MessageBox.Show("是否保存配置参数？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }
            m_Other1Tool.SavePara();
        }
        #endregion

        #region tslAdd_Click 添加
        private void tslAdd_Click(object sender, EventArgs e)
        {
            if (LuxsanTool.MachineWorkManage.m_bStart)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("系统正在运行", "提示");
                return;
            }
            LuxsanBaseHelpLib.LogIn.User user = LuxsanBaseHelpLib.LogIn.LogIn.m_actCuurentUser;
            if (user.iAuthorityLevel < (int)LuxsanBaseHelpLib.LogIn.AuthorityLevel.Engineer)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("权限不足", "提示");
                return;
            }

            switch (((ToolStripStatusLabel)sender).Name)
            {
                #region 添加输入值

                case "tslAddInput":
                    {
                        //int iWith = LuxsanTool.HelpForm.frmAddInputValue.m_Instance.Width;
                        //int iHeight = LuxsanTool.HelpForm.frmAddInputValue.m_Instance.Height;
                        //Point pitMousePosition = Control.MousePosition;
                        //LuxsanTool.HelpForm.frmAddInputValue.m_Instance.SetDesktopLocation(pitMousePosition.X, pitMousePosition.Y - iHeight);
                        LuxsanTool.HelpForm.frmAddInputValue.m_Instance.Initial(m_Other1Tool.m_strStationName, "");
                        LuxsanTool.HelpForm.frmAddInputValue.m_Instance.ShowDialog();
                        if (!LuxsanTool.HelpForm.frmAddInputValue.m_Instance.m_bOkCannel)
                            return;

                        ToolInputValue toolInputValue = LuxsanTool.HelpForm.frmAddInputValue.m_Instance.m_toolInputValue;
                        LuxsanTool.HelpForm.frmAddInputValue.m_Instance.Release();

                        LuxsanBaseHelpLib.ExecuteStatus executeStatus = m_Other1Tool.AddInputValue(toolInputValue);
                        if (!executeStatus.bStatus)
                        {
                            LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show(executeStatus.strErrorMsg, "提示");
                            return;
                        }


                        //显示输入值
                        InPutValueParaToForm();

                        //JudgeToForm();
                    }
                    break;
                #endregion

                #region  删除输入值
                case "tslDeleteInput":
                    {
                        int RowCount = dtInPutValue.Rows.Count;
                        if (RowCount == 0)
                        {
                            LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("输入变量列表没有添加输入变量", "提示");
                            return;
                        }
                        int iSelectDeleteRow = GetSelectedRowIndex(dtInPutValue);
                        if (iSelectDeleteRow < 0)
                        {
                            LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("未选择输入变量", "提示");
                            return;
                        }

                        string strDeleteName = dtInPutValue.Rows[iSelectDeleteRow].Cells[0].Value.ToString();
                        if (MessageBox.Show($"是否删除选择的输入值<{strDeleteName}>?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                        {
                            return;
                        }
                        DeleteDataTable(dataTableInPutValue, strDeleteName);
                        m_Other1Tool.DeleteInputValue(strDeleteName);



                        //显示输入值
                        InPutValueParaToForm();
                        //JudgeToForm();



                        //回调有侦测连接的项目

                    }
                    break;
                #endregion

                #region 调整输入值
                case "tslModifyInput":
                    {
                        int RowCount = dtInPutValue.Rows.Count;
                        if (RowCount == 0)
                        {
                            LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("输入变量列表没有添加输入变量", "提示");
                            return;
                        }
                        int iSelectModifyRow = GetSelectedRowIndex(dtInPutValue);
                        if (iSelectModifyRow < 0)
                        {
                            LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("未选择输入变量", "提示");
                            return;
                        }
                        string strModifyName = dtInPutValue.Rows[iSelectModifyRow].Cells[0].Value.ToString();


                        string InPutResourcesWorkName = m_Other1Tool.m_ToolInputValue[strModifyName].InPutResources.GetWorkName;

                        //int iWith = LuxsanTool.HelpForm.frmModifyInPutValue.m_Instance.Width;
                        //int iHeight = LuxsanTool.HelpForm.frmModifyInPutValue.m_Instance.Height;
                        //Point pitMousePosition = Control.MousePosition;
                        //LuxsanTool.HelpForm.frmModifyInPutValue.m_Instance.SetDesktopLocation(pitMousePosition.X, pitMousePosition.Y - iHeight);
                        LuxsanTool.HelpForm.frmModifyInPutValue.m_Instance.Initial(m_Other1Tool.m_ToolInputValue[strModifyName], InPutResourcesWorkName, "");
                        LuxsanTool.HelpForm.frmModifyInPutValue.m_Instance.ShowDialog();
                        if (!LuxsanTool.HelpForm.frmModifyInPutValue.m_Instance.m_bOkCannel)
                            return;

                        ToolInputValue toolInputValue = LuxsanTool.HelpForm.frmModifyInPutValue.m_Instance.m_toolInputValueNew;
                        LuxsanTool.HelpForm.frmModifyInPutValue.m_Instance.Release();

                        ModifyDataTable(dataTableInPutValue, toolInputValue.strName, strModifyName);


                        //调整
                        LuxsanBaseHelpLib.ExecuteStatus executeStatus = m_Other1Tool.ModifyInputValue(strModifyName, toolInputValue);
                        if (!executeStatus.bStatus)
                        {
                            LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show(executeStatus.strErrorMsg, "提示");
                            return;
                        }
                        //显示输入值
                        InPutValueParaToForm();
                        //回调有侦测连接的项目
                    }
                    break;
                    #endregion

            }

        }
        #endregion

        #region btnRunTool_Click 运行工具
        private void btnRunTool_Click(object sender, EventArgs e)
        {
            if (LuxsanTool.MachineWorkManage.m_bStart)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("系统正在运行", "提示");
                return;
            }
            LuxsanBaseHelpLib.LogIn.User user = LuxsanBaseHelpLib.LogIn.LogIn.m_actCuurentUser;
            if (user.iAuthorityLevel < (int)LuxsanBaseHelpLib.LogIn.AuthorityLevel.Engineer)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("权限不足", "提示");
                return;
            }

            m_Other1Tool.RunTool();
        }
        #endregion

        private void dtInstanceVar_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (LuxsanTool.MachineWorkManage.m_bStart)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("系统正在运行", "提示");
                return;
            }
            dataTableInPutValue.Rows.Clear();
            InPutValueParaToForm();
        }

        private void dtOutPutValue_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (LuxsanTool.MachineWorkManage.m_bStart)
            {
                LuxsanBaseHelpLib.AutoCloseMessageBox.m_Instance.Show("系统正在运行", "提示");
                return;
            }
            dataTableOutputValue.Rows.Clear();
            OutPutValueParaToForm();
        }
        bool bZoom = false;
        float height0 = 70;
        float height2 = 10;
       
        private void StatusStrip1_DoubleClick(object sender, EventArgs e)
        {
            if (!bZoom)
            {
                bZoom = true;
                height0 = tableLayoutPanel_Main2.RowStyles[0].Height;
                height2 = tableLayoutPanel_Main2.RowStyles[1].Height;
                tableLayoutPanel_Main2.RowStyles[0] = new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 70F);
                tableLayoutPanel_Main2.RowStyles[1] = new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F);

            }
            else
            {
                bZoom = false;

                tableLayoutPanel_Main2.RowStyles[0] = new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, height0);
                tableLayoutPanel_Main2.RowStyles[1] = new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, height2);

            }
        }
    }
}







